package com.htl.exampro.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htl.exampro.base.exception.ExamProException;
import com.htl.exampro.base.utils.StringUtil;
import com.htl.exampro.base.utils.UserUtil;
import com.htl.exampro.course.mapper.ChapterMapper;
import com.htl.exampro.course.mapper.CourseMapper;
import com.htl.exampro.course.pojo.domain.CourseDO;
import com.htl.exampro.course.pojo.domain.ChapterDO;
import com.htl.exampro.course.pojo.vo.ChapterVO;
import com.htl.exampro.course.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, ChapterDO>
        implements ChapterService {
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<ChapterVO> getChaptersByCourseId(Long courseId) {
        List<ChapterDO> chapterDOS = lambdaQuery()
                .eq(ChapterDO::getCourseId, courseId)
                .orderByAsc(ChapterDO::getSortOrder)
                .list();
        return BeanUtil.copyToList(chapterDOS, ChapterVO.class);
    }

    @Override
    @Transactional
    public void saveOrUpdateChapters(Long courseId, List<ChapterVO> detailVOS) {

        LambdaQueryWrapper<ChapterDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChapterDO::getCourseId, courseId);
        List<ChapterDO> chapterDOS = baseMapper.selectList(queryWrapper);

        // 批量保存/更新新章节
        List<ChapterDO> detailDOS = BeanUtil.copyToList(detailVOS, ChapterDO.class);
        List<ChapterDO> exists = detailDOS.stream().filter(o -> o.getChapterId() != null).toList();

        List<ChapterDO> list = chapterDOS.stream().filter(o -> exists.stream().noneMatch(e -> e.getChapterId().equals(o.getChapterId()))).toList();
        if (CollUtil.isNotEmpty(list)) {
            baseMapper.deleteByIds(list);
        }

        for (ChapterDO detailDO : exists) {
            LambdaUpdateWrapper<ChapterDO> updateWrapper = new LambdaUpdateWrapper<>();
            baseMapper.update(updateWrapper.eq(ChapterDO::getChapterId, detailDO.getChapterId())
                    .set(ChapterDO::getChapterName, detailDO.getChapterName())
                    .set(ChapterDO::getContent, detailDO.getContent())
                    .set(ChapterDO::getAttachmentUrl, StringUtil.isEmpty(detailDO.getAttachmentUrl()) ? null : detailDO.getAttachmentUrl())
                    .set(ChapterDO::getVideoUrl, StringUtil.isEmpty(detailDO.getAttachmentUrl()) ? null : detailDO.getVideoUrl())
            );
        }

        List<ChapterDO> notExists = detailDOS.stream().filter(o -> o.getChapterId() == null).toList();
        notExists.forEach(o -> {
            o.setCourseId(courseId);
            if (StringUtil.isEmpty(o.getVideoUrl()))
                o.setVideoUrl(null);
            if (StringUtil.isEmpty(o.getAttachmentUrl()))
                o.setAttachmentUrl(null);
        });
        baseMapper.insert(notExists);
    }

    @Override
    public void deleteChapter(Long chapterId) {
        ChapterDO detailDO = baseMapper.selectById(chapterId);
        if (!detailDO.getCreatedPerson().equals(UserUtil.getUserId())) {
            ExamProException.cast(403, "禁止操作！此课程不属于你。");
        }
        baseMapper.deleteById(chapterId);
    }

    @Override
    public void saveChapter(ChapterVO detailVOS) {
        CourseDO courseDO = courseMapper.selectById(detailVOS.getCourseId());
        if (!courseDO.getCreatedPerson().equals(UserUtil.getUserId())) {
            ExamProException.cast(403, "禁止操作！此课程不属于你。");
        }
        ChapterDO chapterDO = BeanUtil.toBean(detailVOS, ChapterDO.class);
        if (StringUtil.isEmpty(chapterDO.getVideoUrl()))
            chapterDO.setVideoUrl(null);
        if (StringUtil.isEmpty(chapterDO.getAttachmentUrl()))
            chapterDO.setAttachmentUrl(null);
        baseMapper.insert(chapterDO);
    }

    @Override
    public void updataChapter(ChapterVO detailVOS) {
        ChapterDO detailDO = baseMapper.selectById(detailVOS.getCourseId());
        if (!detailDO.getCreatedPerson().equals(UserUtil.getUserId())) {
            ExamProException.cast(403, "禁止操作！此课程不属于你。");
        }
        ChapterDO chapterDO = BeanUtil.toBean(detailVOS, ChapterDO.class);
        if (StringUtil.isEmpty(chapterDO.getVideoUrl()))
            chapterDO.setVideoUrl(null);
        if (StringUtil.isEmpty(chapterDO.getAttachmentUrl()))
            chapterDO.setAttachmentUrl(null);
        baseMapper.updateById(chapterDO);
    }
}